# -*- coding:utf-8 -*-
from common.my_time import MyTime
import re
import threading
import hashlib
import time
import os
import shutil
from base import Base
from common.custom_task_data import CustomTaskData
import datetime

'''
定制任务处理
'''


class ZixunItem:
    def __init__(self, data_date, data_title, data_url, data_site):
        self.Data_date = data_date
        self.Data_title = data_title
        self.Data_url = data_url
        self.Data_site = data_site
    def GetKey(self):
        return self.Data_date

def GetZixunKey(d):
    return d.GetKey()

class CustomTaskWriteFile(Base):
    def __init__(self, log_file):
        self.custom_task = CustomTaskData()
        self.url = ""
        self.file_handler = ""
        self.news = []
        self.record_title = False
        self.zixun_cache = []
        self.task_id = 0
        
    def __del__(self):
        pass

    def write_file_head(self, task_date, entity_name, start_date, custom_word):
        keyword = "say by data," + entity_name + "," + custom_word
        title = entity_name + "资讯"
        self.file_handler.write("<?php\n")
        self.file_handler.write("require_once rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/site/config.php';\n")
        self.file_handler.write("include_once GLOBAL_PHP.'view.php';\n")
        self.file_handler.write("DisplayHead(array('keyword' => '" + keyword + "'));\n")
        self.file_handler.write("?>\n")
        self.file_handler.write("<div class=\"div_main_frame\" style=\"margin:0px;padding:12px;width:95%\">")
        self.file_handler.write("<div class=\"div_link_rank_title\" style=\"line-height:46px;font-size:30px;text-align:center;\">" + title + "</div>\n")
        self.file_handler.write("<div class=\"div_link_rank_content\" style=\"text-align:center;\">关键词:" + custom_word + "</div>\n")
        self.file_handler.write("<div class=\"div_link_rank_content\" style=\"text-align:center;\">时间:" + str(start_date) + "~" + str(task_date) + "</div>\n")

    def write_file_tail(self):
        self.file_handler.write("<div style=\"clear:both\"></div></div>\n")
        self.file_handler.write("<?php\n")
        self.file_handler.write("DisplayTail();\n")
        self.file_handler.write("?>\n")

    def recode_data(self, data_date, data_title, data_url, data_site):
        self.custom_task.add_task_detail_data(self.task_id, data_date, data_title, data_url, data_site)
        return
        if data_title in self.news:
            return;

        self.zixun_cache.append(ZixunItem(data_date, data_title, data_url, data_site))
        self.news.append(data_title)
        return

        '''
        if self.record_title == False:
            self.record_set_name(s)
            self.record_title = True
        '''
        self.file_handler.write("<li  class=\"fastweb_tree_leaf\"><a href=\"" + data_url + "\">[" + data_site + "]["+ data_date + "]" + data_title + "</a></li>\n")
        #self.file_handler.write("<div class=\"div_link_rank_content\" style=\"margin:0px;padding:0px;\"><a href=\"" + data_url + "\">[" + data_site + "]["+ data_date + "]" + data_title + "</a></div>\n")
        self.news.append(data_title)

    def write_cache_data(self):
        self.zixun_cache.sort(key=GetZixunKey,reverse=True)
        for d in self.zixun_cache:
            self.file_handler.write("<li  class=\"fastweb_tree_leaf\"><a href=\"" + d.Data_url + "\">[" + d.Data_site + "]["+ d.Data_date + "]" + d.Data_title + "</a></li>\n")

    def write_db_data(self):
        for d in self.custom_task.query_task_detail_data(self.task_id):
            self.file_handler.write("<li  class=\"fastweb_tree_leaf\"><a href=\"" + d[3] + "\">[" + d[0] + "]["+ str(d[2]) + "]" + d[1] + "</a></li>\n")



    def record_set_name(self, set_name):
        self.file_handler.write("<div class=\"div_link_rank_title\" >" + set_name + "</div>\n")
        self.news = []

    def do_search(self, sets, pre_attr, post_attr, custom_word, custom_array):
        for s in sets:
            if s == "":
                continue
            #定制词与实体相同，说明是在查询两者关系，忽略与自身关系
            if s == custom_word:
                continue
            #self.record_set_name(s)
            #self.record_title = False
            search_word = []
            result_check = [[s]]
            if pre_attr != "":
                search_word.append(pre_attr)
            search_word.append("\"" + s + "\"")
            if post_attr != "":
                search_word.append(post_attr)
            if custom_word != "":
                search_word.append(custom_word)
                result_check.append(custom_array)
            #self.get_data(search_word, result_check, ["?",";","-"])
            self.get_data_dingzhi(search_word, result_check)
    
    def record_task_class2(self):
        #file_handler.write("<div class=\"div_link_rank_title\" style=\"margin:0px;padding:0px;\">" +  name + "</div>\n")
        self.file_handler.write("<li  class=\"fastweb_tree_nav\"><input type=\"checkbox\" class=\"fastweb_tree_input\" checked=\"checked\"/><ol>\n")

    def get_begin_date(self, start_date):
        d = self.custom_task.query_task_max_date(self.task_id)
        if len(d) == 0:
            return start_date
        print(str(d[0][0] + datetime.timedelta(-3)))
        return d[0][0] + datetime.timedelta(-3)

    def generate_file(self, task_date, entity_name, start_date, custom_word, file):
        temp = str(task_date) + str(start_date) + entity_name + custom_word
        new_start_date = self.get_begin_date(start_date)
        self.set_end_date(str(new_start_date))
        self.set_max_page(20)
        self.set_check_title(False)
        file_name = file.replace("files/", "")
        folder = "files"
        if file_name == "":
            file_name = hashlib.md5(temp.encode(encoding="UTF-8")).hexdigest() + ".php"
        self.file_handler = open(file_name, 'w', encoding = 'utf-8')
        self.write_file_head(task_date, entity_name, start_date, custom_word)
        self.url = folder + "/" + file_name
        #self.url = str(task_date) + "/" + file_name
        entitys = self.custom_task.query_entity_info(entity_name)

        self.file_handler.write("<ol class=\"fastweb_tree\">\n")
        self.record_task_class2()
        '''
        for entity in entitys:
            sets = entity[2].split("|")

            if custom_word == "":
                self.do_search(sets, entity[0], entity[1], "", [])
            else:
                i = 0
                custom_word_split = custom_word.split(",")
                for single_word in custom_word_split:
                    i += 1
                    #定制词过多，系统压力大
                    if i > 5:
                        break
                    self.do_search(sets, entity[0], entity[1], single_word, custom_word_split)
        '''

        #self.write_cache_data()
        self.write_db_data()
        self.file_handler.write("</ol></li>\n")
        self.file_handler.write("</ol>\n")

        self.write_file_tail()
        self.file_handler.close()
        is_exists = os.path.exists("/home/saybydata_static/" + folder)
        if not is_exists:
            os.makedirs("/home/saybydata_static/" + folder)
        shutil.move(file_name, "/home/saybydata_static/" + folder + "/" + file_name)

    def process(self):
        tasks = self.custom_task.query_task_for_write()
        for task in tasks:
            self.task_id = task[0]
            #self.custom_task.update_task(task[0], 1, "")
            self.generate_file(task[1], task[2], task[3], task[4], task[5])
            self.custom_task.update_task(task[0], 2, self.url)
        '''
        if len(tasks) <= 5:
            t = datetime.datetime.now()
            current_date = (t + datetime.timedelta(days=0)).strftime("%Y-%m-%d")
            old_date = (t + datetime.timedelta(days=0)).strftime("%Y-%m-%d")
            old_tasks = self.custom_task.query_old_task(old_date)
            for task in old_tasks:
                self.custom_task.update_old_task(task[0], str(task[1]), current_date)
        '''
def custom_task_write_file_api():
    task = CustomTaskWriteFile("./out/custom_task_write_file.log")
    task.process()

if __name__ == '__main__':
    custom_task_write_file_api()


